package com.example.config;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.JSONUtil;
import com.example.entity.ShopList;
import com.example.mapper.ShopListMapper;
import com.example.result.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: tobed
 * @date: 2022/11/22
 * @time: 9:05
 */
@ServerEndpoint(value = "/socketJob/{text}")
@Component
public class WebSocketJob {

    @Autowired
    ShopListMapper shopListMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    public static final Map<String, Session> sessionMap = new ConcurrentHashMap<>();

    @OnOpen
    public void hah(@PathParam("text") String text){
        System.out.println(text);
    }

    @OnMessage
    public int onMessage(String message) {
        System.out.println(message);
        if (message.equals("哈哈哈")){
            return 1;
        }else{
            return 0;
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("-----异常警报-----");
        error.printStackTrace();
    }

    /**
     * 服务端发送消息给所有客户端
     */
    private void sendAllMessage(String message) {
        try {
            for (Session session : sessionMap.values()) {
                session.getBasicRemote().sendText(message);
            }
        } catch (Exception e) {
            System.out.println("服务端发送消息给客户端失败" + e);
        }
    }

    private CommonResult returnList(){
        List<ShopList> shopLists = JSONUtil.toBean(stringRedisTemplate.opsForValue().get("ShopList"), new TypeReference<List<ShopList>>() {
        }, true);
        return CommonResult.ok(shopLists);
    }

}
